import 'package:find_friend/common/alert_tool.dart';
import 'package:find_friend/common/event_bus.dart';
import 'package:find_friend/const/const.dart';
import 'package:find_friend/network/network.dart';
import 'package:find_friend/pages/im/model/groupmodel.dart';
import 'package:flutter/material.dart';

class MsgGroupManagerPage extends StatefulWidget {

  @override
  _MsgGroupManagerPageState createState() => _MsgGroupManagerPageState();
}

class _MsgGroupManagerPageState extends State<MsgGroupManagerPage> {
  
  TextEditingController _textEditingController = TextEditingController();
  
  int deleIndex = -1;

  List<GroupModel> list = [];

  int selectid = -1;

  _requestGroup({String name}) {

    Map<String, dynamic> params = {};
    if(name != null) {  
      params["name"] = name;
    }
    Networktool.request(API.friendgroup, params: params,method: name == null ? NETWORKHTTPMethod.GET : NETWORKHTTPMethod.POST, success: (data){
      if(data != null) {
        IMGroupResponse response = IMGroupResponse.fromJson(data);
        list = response.data;
        list.removeWhere((element) => element.id <= 0);
        if(mounted) setState(() {});
        _refreshGroup();
      }
    });
  }

  _requestDelGroup(GroupModel model) {
    Networktool.request(API.friendgroup + "/${model.id}", method: NETWORKHTTPMethod.DELETE, success: (data){
      if(data != null) {
        setState(() {
          deleIndex = -1;
          list.remove(model);
        });
        _refreshGroup();
      }
    });
  }

  // 分组排序
  _requestSort() {
    String sort = list.map((e) => e.id).join(",");
    Networktool.request(API.friendgroupsort, params: {"sort": sort}, success: (data){
      if(data != null) {
        _refreshGroup();
        Navigator.of(context).pop();
      }
    });
  }

  _requestModGroup(GroupModel model) {
    Networktool.request(API.friendgroup + "/${model.id}", params: {"name": model.friendgroup}, method: NETWORKHTTPMethod.PUT, success: (data){
      if(data != null) {
        setState(() {
        });
        _refreshGroup();
      }
    });
  }

  _refreshGroup() {
    EventMineBus.instance.commit(EventMineKeys.IMGroupRefresh, null);
  }



  @override
  void initState() {
    super.initState();
    _requestGroup();
  }

  @override
  void dispose() {
    _textEditingController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // backgroundColor: Colors.white,
      appBar: AppBar(
        title: Text("分组管理"),
        backgroundColor: Colors.white,
        centerTitle: true,
        leading: IconButton(
          onPressed: (){
            Navigator.of(context).pop();
          },
          icon: Image.asset("assets/fanhui.png"),
        ),
        actions: [
          FlatButton(
            onPressed: _requestSort,
            child: Text("完成", style: instanceTextStyle(14, APP_font_black)),
          )
        ],
      ),
      body: Container(
        padding: const EdgeInsets.all(10),
        child: Column(
          children: [
            GestureDetector(
              onTap: (){
                AlertTool.showInputDialog(context, _textEditingController, title: "编辑分组\n请输入新的分组名称", placeholder: "请输入分组名称", sureCallback: (val){
                  if(val == "") return;
                  _textEditingController.clear();
                  _requestGroup(name: val);
                });
              },
              child: Row(
                children: [
                  Image.asset("assets/tianjia.png", width: 35,),
                  SizedBox(width: 5,),
                  Text("添加分组", style: instanceTextStyle(14, APP_font_black),)
                ],
              ),
            ),
            SizedBox(height: 10,),
            Expanded(
              child: Container(
                child: ReorderableListView(
                  onReorder: (oldIndex, newIndex){
                    final item = list[oldIndex];
                    setState(() {
                      list.insert(newIndex, item);
                      if(oldIndex < newIndex){
                        list.removeAt(oldIndex);
                      } else {
                        list.removeAt(oldIndex + 1);
                      }
                    });
                  },
                  
                  children: list.map((e){
                    bool del = list.indexOf(e) == deleIndex;
                    return _GroupCell(
                      key: ValueKey(e), 
                      title: e.friendgroup, 
                      isdelete: del,
                      onTapDelete: (){  // 点击删除分组
                        AlertTool.showConfirmDialog(context, title: "删除该分组后\n组内联系人将移至默认分组", sureCallback: (){
                          deleIndex = -1;
                          _textEditingController.clear();
                          _requestDelGroup(e);
                        });
                      },
                      onOpenDelete: (){ // 显示删除按钮
                        var val = list.indexOf(e);
                        if(val == deleIndex){
                          setState(() {
                            deleIndex = -1;
                          });
                        } else {
                          setState(() {
                            deleIndex = val;
                          });
                        }
                      },
                      onTapName: (){ // 修改名字
                        _textEditingController.text = e.friendgroup;
                        AlertTool.showInputDialog(context, _textEditingController, title: "编辑分组\n请输入新的分组名称", placeholder: "请输入分组名称", sureCallback: (str){
                          e.friendgroup = str;
                          _requestModGroup(e);
                        });
                      },
                    );
                  }).toList()
                ),
              ),
            )
          ],
        ),
      ),
    );
  }


}

class _GroupCell extends StatelessWidget {

  final String title;
  final bool isdelete;
  final Function onOpenDelete;
  final Function onTapDelete;
  final Function onTapName;

  const _GroupCell({Key key, this.title, this.isdelete = false, this.onOpenDelete, this.onTapDelete, this.onTapName}) : super(key: key);

  Widget _buildDelete() {
    if(isdelete) {
      return GestureDetector(
        onTap: onTapDelete,
        child: Container(
          decoration: BoxDecoration(
            color: APP_verify_error_color,
            borderRadius: BorderRadius.circular(15)
          ),
          padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 3),
          child: Text("删除", style: instanceTextStyle(14, Colors.white),),
        ),
      );
    } else {
      return Icon(Icons.reorder, color: APP_divider_color,);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10),
      height: 45,
      child: Row(
        children: [
          GestureDetector(
            onTap: onOpenDelete,
            child: Image.asset("assets/shanchufenzu.png"),
          ),
          SizedBox(width: 12.5,),
          Expanded(child: GestureDetector(
            onTap: onTapName,
            child: Text(title, style: instanceTextStyle(14, APP_font_black),)
          ),),
          _buildDelete()
        ],
      ),
    );
  }
}